<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div>
            <div class="text-center">
              <userAvatar />
            </div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />用户名称
                <div class="pull-right">{{ user.userName }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />手机号码
                <div class="pull-right">{{ user.phonenumber }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="email" />用户邮箱
                <div class="pull-right">{{ user.email }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />所属部门
                <div class="pull-right" v-if="user.dept">{{ user.dept.deptName }} / {{ postGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="peoples" />所属角色
                <div class="pull-right">{{ roleGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="date" />创建日期
                <div class="pull-right">{{ user.createTime }}</div>
              </li>
            </ul>
            <!-- 机器人地址配置表单已移除 -->
          </div>
        </el-card>
      </el-col>
      <el-col :span="18" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>基本资料</span>
          </div>
          <el-tabs v-model="selectedTab">
            <el-tab-pane label="基本资料" name="userinfo">
              <userInfo :user="user" />
              <!-- 机器人地址配置表单，已移到基本资料tab内 -->
              <div style="margin-top: 20px;">
                <el-divider>机器人地址配置</el-divider>
                <el-form :model="botForm" :rules="botRules" ref="botForm" label-width="80px" size="small">
                  <el-form-item
                    v-for="(item, index) in botForm.botUrls"
                    :key="index"
                    :label="'地址' + (index + 1)"
                    :prop="'botUrls.' + index + '.url'"
                    :rules="botUrlRules"
                  >
                    <el-input
                      v-model="item.url"
                      placeholder="请输入机器人地址"
                      style="width: calc(100% - 80px); margin-right: 10px;"
                    />
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="removeBotUrl(index)"
                      v-if="botForm.botUrls.length > 1"
                    >
                      删除
                    </el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      @click="addBotUrl"
                      v-if="botForm.botUrls.length < 3"
                    >
                      新增机器人地址
                    </el-button>
                    <el-button type="success" @click="submitBotUrls">保存</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="resetPwd">
              <resetPwd />
            </el-tab-pane>
          </el-tabs>
        </el-card>
        <!-- 新增本家地址配置卡片 -->
        <el-card v-if="user.roles[0].dataScope == 4" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>本家地址配置</span>
          </div>
          <el-form :model="addressForm" :rules="addressRules" ref="addressForm" label-width="80px">
            <el-form-item label="本家地址" prop="httpUrl">
              <el-input v-model="addressForm.httpUrl" placeholder="请输入HTTP地址" />
            </el-form-item>
            <el-form-item label="本家账号" prop="httpUser">
              <el-input v-model="addressForm.httpUser" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="本家密码" prop="httpPwd">
              <el-input v-model="addressForm.httpPwd" placeholder="请输入密码" show-password />
            </el-form-item>
            <el-form-item label="派单模式" prop="dispatchMode">
              <el-radio-group v-model="addressForm.dispatchMode">
                <el-radio label="0">使用上家地址直接派单</el-radio>
                <el-radio label="1">使用本家地址派单</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitAddress">保存</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import userAvatar from "./userAvatar"
import userInfo from "./userInfo"
import resetPwd from "./resetPwd"
import { getUserProfile } from "@/api/system/user"
import axios from "axios";

export default {
  name: "Profile",
  components: { userAvatar, userInfo, resetPwd },
  data() {
    return {
      user: {},
      roleGroup: {},
      postGroup: {},
      selectedTab: "userinfo",
      // 新增本家地址配置表单
      addressForm: {
        httpUrl: '',
        httpUser: '',
        httpPwd: '',
        dispatchMode: '0'
      },
      addressRules: {
        httpUrl: [{ required: true, message: 'HTTP地址不能为空', trigger: 'blur' }],
        httpUser: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
        httpPwd: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        dispatchMode: [{ required: true, message: '请选择派单模式', trigger: 'change' }]
      },
      // 新增机器人地址配置表单
      botForm: {
        botUrls: [{ url: '' }]
      },
      botRules: {
        botUrls: [{ type: 'array', required: true, message: '机器人地址不能为空', trigger: 'change' }]
      },
      botUrlRules: [{ required: true, message: '机器人地址不能为空', trigger: 'blur' }]
    }
  },
  created() {
    const activeTab = this.$route.params && this.$route.params.activeTab
    if (activeTab) {
      this.selectedTab = activeTab
    }
    this.getUser()
  },
  methods: {
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data
        this.roleGroup = response.roleGroup
        this.postGroup = response.postGroup
        // 同步本家地址配置
        this.addressForm.httpUrl = this.user.dept.httpUrl || ''
        this.addressForm.httpUser = this.user.dept.httpUser || ''
        this.addressForm.httpPwd = this.user.dept.httpPwd || ''
        this.addressForm.dispatchMode = (this.user.dept && this.user.dept.dispatchMode) || this.user.dispatchMode || '0'
        // 同步机器人地址配置
        if (this.user.botUrls && Array.isArray(this.user.botUrls) && this.user.botUrls.length > 0) {
          this.botForm.botUrls = this.user.botUrls.map(url => ({ url: url }))
        } else {
          this.botForm.botUrls = [{ url: '' }]
        }
      })
    },
    // 新增保存本家地址配置方法
    submitAddress() {
      this.$refs.addressForm.validate(valid => {
        if (valid) {
          // 合并到user对象
          const data = {
            ...this.user,
            httpUrl: this.addressForm.httpUrl,
            httpUser: this.addressForm.httpUser,
            httpPwd: this.addressForm.httpPwd,
            dispatchMode: this.addressForm.dispatchMode
          }
          // 复用基本资料保存接口
          this.$modal.loading("正在保存，请稍候...")
          import("@/api/system/user").then(module => {
            module.updateUserProfile(data).then(res => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess("保存成功")
              // 更新user对象
              this.user.httpUrl = this.addressForm.httpUrl
              this.user.httpUser = this.addressForm.httpUser
              this.user.httpPwd = this.addressForm.httpPwd
              this.user.dispatchMode = this.addressForm.dispatchMode
            }).catch(() => {
              this.$modal.closeLoading()
            })
          })
        }
      })
    },
    // 新增添加机器人地址方法
    addBotUrl() {
      this.botForm.botUrls.push({ url: '' })
    },
    // 新增删除机器人地址方法
    removeBotUrl(index) {
      this.botForm.botUrls.splice(index, 1)
    },
    // 新增保存机器人地址方法
    submitBotUrls() {
      this.$refs.botForm.validate(valid => {
        if (valid) {
          // 过滤掉空的地址
          const validUrls = this.botForm.botUrls
            .map(item => item.url)
            .filter(url => url && url.trim() !== '')

          // 只提交必要的用户字段，避免影响其他表单数据
          const data = {
            userId: this.user.userId,
            userName: this.user.userName,
            nickName: this.user.nickName,
            email: this.user.email,
            phonenumber: this.user.phonenumber,
            sex: this.user.sex,
            userValidityPeriod: this.user.userValidityPeriod,
            botUrls: validUrls
          }
          this.$modal.loading("正在保存，请稍候...")
          import("@/api/system/user").then(module => {
            module.updateUserProfile(data).then(res => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess("保存成功")
              this.user.botUrls = validUrls
            }).catch(() => {
              this.$modal.closeLoading()
            })
          })
        }
      })
    }
  }
}
</script>
